package com.qdsg.modulesihealsdk.ecgSingle.draw;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff.Mode;
import android.os.Environment;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.qdsg.modulesihealsdk.ecgSingle.callback.ECGSingleCallback;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;


/**
 * @author fangrf 2018/12/20
 */
public class ECGReportSurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable{
	private  final String TAG ="ECGReportSurfaceView";
	
    private SurfaceHolder surfaceHolder;
	private int bgColor = Color.WHITE;//Color.BLACK;
	public int waveSpeed = 25;// speed: 25mm/s
	/** 1s = 6个数据包 ,1包25点 = 25* 6 = 150 ,1ms = 0.15点
	 * 1s = 6 packet, 1 packet was 25 data,1s=25*6=150 data, 1ms=0.15 data
	 * the draw time for lockCavas */ 
	private int sleepTime = 20; // 每次锁屏的时间间距(帧率)，单位:ms  1ms=1.5个点
	private float lockWidth;// 每次锁屏需要画的
	private int ecgPerCount = 3;// 每次画心电数据的个数， 20*0.15
	private Paint mPaint;// 画波形图的画笔
	private int surfaceWidth;
	private int surfaceHeight;
	private float startX;//每次画线的X坐标起点
	private float startY;
	private double ecgXOffset;//每次X坐标偏移的像素
	private float ecgYOffset;
	private int areaHeight;//绘制1行波形的区域
	public int waveColor = 0xff2E8B57;//Color.GREEN;
	public int mGridColor = 0xffFFB6C1;//Color.DKGRAY;//Color.parseColor("#1b4200");
	private float mGridWidth = 50;
	public int textColor = Color.BLUE;
	private int waveWidth=2;
	public int divisionLineColor = Color.GRAY;//Color.BLUE;//分割线颜色,每6格高度一条水平线
	
	public ECGReportSurfaceView(Context context) {
		this(context, null);
	}

	public ECGReportSurfaceView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private Bitmap bitmapCache;
	private Canvas canvasCache;
	private void init() {
		surfaceHolder = getHolder();
		surfaceHolder.addCallback(this);
		mPaint = new Paint();
		mPaint.setStyle(Style.STROKE);
		mPaint.setColor(waveColor);// Color.parseColor(bgColor)
		mPaint.setStrokeWidth(waveWidth);
		mPaint.setAntiAlias(true);
		mPaint.setTextSize(50);

	}

	@Override //2
	public void surfaceCreated(SurfaceHolder holder) {
		surfaceWidth = getWidth();
		surfaceHeight = getHeight();
		//Log.d(TAG, "surfaceWidth:"+surfaceWidth+",surfaceHeight:"+surfaceHeight);
		bitmapCache = Bitmap.createBitmap(surfaceWidth,surfaceHeight, Bitmap.Config.ARGB_8888); 
		canvasCache = new Canvas(bitmapCache); 
	    	
		converXOffset();	
		
	    new Thread(this).start();	             
	}

	@Override //3
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	}
	
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		ecgQueue.clear();
	}


	public void surfaceDestroyed() {
		ecgQueue.clear();
	}
    /**
     * 根据波速计算每次X坐标增加的像素
     */
    @SuppressLint("NewApi")
	private void converXOffset(){                  
        //缩放比例,固定3行，每行50格,1格代表5mm,走速25mm/s
    	//fixed 3 rows, 50 grid was in 1 row,1 grid meaning 5mm width of grid
    	//ecg wave speed was 25mm/s, so 1 row was 10 second wave data(10s*25mm/s=5mm*50),
    	//total 30s ecg wave data
        mGridWidth = surfaceWidth /50f;//10s = 50格 ,10s= 50 grid width
        float px1mm = mGridWidth /5f;
        float px1s = waveSpeed * px1mm;
        //每次锁屏所需画的宽度,  the width for lockCanvas 
        lockWidth = px1s * (sleepTime / 1000f);        
        ecgYOffset = mGridWidth * 3;
        //Log.d(TAG, "mGridWidth:"+mGridWidth+",getHeight():"+getHeight());
		
        startY = ecgYOffset;// 初始Y坐标, init Y coordinate
		areaHeight = (int) (2*ecgYOffset);
		ecgXOffset = lockWidth / ecgPerCount;
    }
    

	@Override
	public void run() {	
        Canvas canvas = surfaceHolder.lockCanvas();
        if(canvas == null) {
			return;
		}
        drawBackground(canvasCache);
        drawECGphoto(canvasCache);
        drawResultText(canvasCache);
        canvas.drawBitmap(bitmapCache,0,0,mPaint);  
        surfaceHolder.unlockCanvasAndPost(canvas);
		createCanvasPhoto();
	}

	public void createCanvasPhoto() {
		Canvas canvas = surfaceHolder.lockCanvas();

		if(canvas == null) {
			// 生成本地图片
			saveMyBitmap("ecg", bitmapCache);
			return;
		} else {
			//放在坐标为0,0的位置
			canvas.drawBitmap(bitmapCache, 0, 0, null);
			saveMyBitmap("ecg", bitmapCache);
			surfaceHolder.unlockCanvasAndPost(canvas);
			surfaceHolder.removeCallback(this);

//			surfaceDestroyed();
		}


	}


	private void saveMyBitmap(final String bitName, final Bitmap bitmap) {
		ECGSingleCallback.getInstance(null).iecgSingle.getBitmap(bitmap);
		new Thread(new Runnable() {
			@Override
			public void run() {
//                Looper.perpare();//增加部分
				String filePath = Environment.getExternalStorageDirectory().getPath();
				File file = new File(filePath + "/PC80B/" + bitName + ".png");
				try {
					file.createNewFile();

					FileOutputStream fOut = null;
					fOut = new FileOutputStream(file);
					bitmap.compress(Bitmap.CompressFormat.PNG, 30, fOut);
					Message msg = Message.obtain();
					msg.obj = file.getPath();

					fOut.flush();
					fOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
        

	private int yRowIndex;//y轴行数计数	
	private void drawECGphoto(Canvas canvas) {
		mPaint.setColor(waveColor);	
		mPaint.setStrokeWidth(waveWidth);
		int size = ecgQueue.size();
        for(int i=0;i<size;i++){        	      
            float newX = (float) (startX + ecgXOffset);
            float newY;
            newY = getYECG(ecgQueue.poll());
            
            int yOffset = yRowIndex*areaHeight;
            canvas.drawLine(startX, startY+yOffset, newX, newY+yOffset, mPaint);
            startX = newX;
            startY = newY;	

            if(startX > surfaceWidth){
                startX = 0;
                yRowIndex ++;      
            }         
        }
	}
	
	//PC-80B is 12 bit ECG
	public boolean is8bitECG;
	public int gain = 1;
	/**
	 * 将心电数据转换成用于显示的Y坐标
	 * @param data
	 * @return
	 */
	private float getYECG(int data){
		float d = 0;			
		if (is8bitECG) { //wave Y nMax = 255
			data -= 128;// it was ECG baseLine value										
			d = areaHeight / 2 - (data * gain);
			
		} else { //12 bit ECG,  wave Y nMax = 4095
			data -= 2048; // it was ECG baseLine value
			d = areaHeight - (data * gain + 2048) / 4096f * areaHeight;
			//Log.i(TAG, "gain-->"+gain);
		}
		return d;
	}
	
	/** 清屏  */
	public void cleanScreen() {
		startX = 0;
		startY = ecgYOffset;
		yRowIndex = 0;
		Canvas canvas = surfaceHolder.lockCanvas(null);
		if(canvas == null) {
			return;
		}
		canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
		drawBackground(canvas);
        surfaceHolder.unlockCanvasAndPost(canvas);
	}
		
	private void drawBackground(Canvas canvas) {
		canvas.drawColor(bgColor);//清屏作用  clean background
		//mPaint.setColor(mGridColor);
		mPaint.setStrokeWidth(1);     
		//画横线  horizon line
		for(float dh = 0,index =0; dh <= surfaceHeight; dh += mGridWidth,index++){
			//canvas.drawLine(0,dh,surfaceWidth,dh,mPaint);
			if ((index%6 == 0) && index!=0) {//画每一行的分割线,1行6格
				mPaint.setColor(divisionLineColor);
			}else {
				mPaint.setColor(mGridColor);
			}
			canvas.drawLine(0,dh,surfaceWidth,dh,mPaint);
		}
		mPaint.setColor(mGridColor);
		//画竖线  vertical line
		for(float dw = 0; dw <= surfaceWidth; dw += mGridWidth){
			canvas.drawLine(dw,0,dw,surfaceHeight,mPaint);
		}       
    }
		
	private void drawResultText(Canvas canvas){	
		if(resultText!=null){
			canvas.drawText(resultText, 20, surfaceHeight/2+100, mPaint);
		}
	}
	
	private String resultText;
	public void setResultText(String text){
		resultText = text;
	}
	
    private Queue<Integer> ecgQueue = new LinkedList<Integer>();	
    public void addWaveData(List<Integer> datas){
    	ecgQueue.addAll(datas);
    } 


   
}
